import axios from "axios";
import storage from "./storage.js";
import store from '../store';

import { ElMessage, ElLoading } from "element-plus";

/**
 * 请求错误处理逻辑
 * @param {*} status
 * @param {*} message
 */
function errorHandler(status, message = null) {
	switch (status) {
		case 401:
			ElMessage.error('尚未登录，请先登录')
			store.dispatch('logout')
			break;
		case 403:
			ElMessage.error('权限不足！')
			break;
		case 404:
			ElMessage.error('请求地址不存在')
			break;
		case 500:
			ElMessage.error('服务器内部错误')
			break;
		case 504:
			ElMessage.error('服务器响应超时')
			break;
		default:
			ElMessage.error(message);
			store.dispatch('logout')
	}
}

let baseUrl = import.meta.env.VITE_API_BASEURL;

const http = axios.create({ baseURL: baseUrl, timeout: 60 * 1000 * 5 });
// 请求前预处理
http.interceptors.request.use(request => {
	request.headers["Authorization"] = storage.getVoucher()
	return request;
}, error => Promise.reject(error));

http.loadingInstance = null;

// 请求后预处理
http.interceptors.response.use((response) => {
	if (http.loadingInstance) http.loadingInstance.close();
	return response.data;
}, error => {
	if (http.loadingInstance) http.loadingInstance.close();
	const status = error['response'] ? error.response.status : 500,
		message = error['response'] ? error.response.statusText : error.message;
	errorHandler(status, message);
	return Promise.reject(error);
});

// 请求时展示loading 的配置
const loadingConfig = {
	lock: true, background: 'rgba(0, 0, 0, 0.1)',
}

function doRequest(config, loading) {
	http.loadingInstance = loading ? ElLoading.service(loadingConfig) : null;
	return http.request(config).catch(err => null)
}

export default {
	baseUrl,
	request: doRequest,
	get: (url, params, loading = false) => {
		return doRequest({ url: url, params: params }, loading)
	},
	put: (url, params, loading = false) => {
		return doRequest({ url: url, method: "PUT", data: params }, loading)
	},
	post: (url, params, loading = false) => {
		return doRequest({ url: url, method: "POST", data: params }, loading)
	},
	delete: (url, params, loading = false) => {
		return doRequest({ url: url, method: "DELETE", params: params }, loading)
	},
	upload: (file, business, loading = false) => {
		let dataForm = new FormData();
		dataForm.append('file', file);
		dataForm.append('business', business);
		let header = { 'Content-Type': 'multipart/form-data' };
		return doRequest({ url: '/upload', method: "POST", data: dataForm, headers: header }, loading)
	}
}
